/*
 * NewOkCancelDialog.java
 *
 * Created on 15 de mayo de 2006, 03:16 AM
 */

package inc.jmc.cyberboard.ui;
import inc.jmc.cyberboard.common.ImageLoader;
import inc.jmc.cyberboard.dao.AccountUserDao;
import inc.jmc.cyberboard.dao.Dao;

import java.sql.Connection;
import java.sql.SQLException;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;
/**
 *
 * @author  Juan Miguel Olguin Salguero
 */
public class LoginFrm extends javax.swing.JDialog {
    /**
	 * 
	 */
	private static final long serialVersionUID = 33578272509017841L;
	static Logger logger = Logger.getLogger(LoginFrm.class.getName());
    /** A return status code - returned if Cancel button has been pressed */
    public static final int RET_CANCEL = 0;
    /** A return status code - returned if OK button has been pressed */
    public static final int RET_OK = 1;
    public String id_user=null;
    public String user=null;
    public String tipoUsuario=null;
    public String innerLogin=null;
    
    /** Creates new form NewOkCancelDialog */
    public LoginFrm(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        userTxt.setText("admin");
        passwordTxt.setText("htmjmc07");
        //this.setImage(ImageLoader.images[ImageLoader.ICON_FRAME_MAIN].getImage());
        candadoLabel.setIcon(ImageLoader.images[ImageLoader.CANDADO]);
        this.setSize(336,152);
    }
    
    /** @return the return status of this dialog - one of RET_OK or RET_CANCEL */
    public int getReturnStatus() {
        return returnStatus;
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        candadoLabel = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        cancelButton = new javax.swing.JButton();
        entrarButton = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        userTxt = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        passwordTxt = new javax.swing.JPasswordField();

        setTitle("Login CyberCoffeeNet");
        setResizable(false);
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentResized(java.awt.event.ComponentEvent evt) {
                formComponentResized(evt);
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                closeDialog(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        jPanel2.setLayout(null);

        jPanel2.setOpaque(false);
        jPanel2.setPreferredSize(new java.awt.Dimension(95, 110));
        candadoLabel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        jPanel2.add(candadoLabel);
        candadoLabel.setBounds(10, 10, 70, 70);

        jPanel1.add(jPanel2, java.awt.BorderLayout.WEST);

        jPanel3.setLayout(null);

        cancelButton.setMnemonic('c');
        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jPanel3.add(cancelButton);
        cancelButton.setBounds(140, 90, 80, 23);

        entrarButton.setMnemonic('e');
        entrarButton.setText("Entrar");
        entrarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                entrarButtonActionPerformed(evt);
            }
        });

        jPanel3.add(entrarButton);
        entrarButton.setBounds(60, 90, 80, 23);

        jLabel1.setText("Usuario");
        jPanel3.add(jLabel1);
        jLabel1.setBounds(10, 20, 60, 20);

        userTxt.setFont(new java.awt.Font("Dialog", 0, 14));
        userTxt.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        userTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                userTxtKeyReleased(evt);
            }
        });

        jPanel3.add(userTxt);
        userTxt.setBounds(80, 10, 140, 30);

        jLabel2.setText("Password");
        jPanel3.add(jLabel2);
        jLabel2.setBounds(10, 60, 60, 20);

        passwordTxt.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
        passwordTxt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                passwordTxtKeyReleased(evt);
            }
        });

        jPanel3.add(passwordTxt);
        passwordTxt.setBounds(80, 50, 140, 30);

        jPanel1.add(jPanel3, java.awt.BorderLayout.CENTER);

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void passwordTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordTxtKeyReleased

        if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
        {
        	userTxt.requestFocus();
            entrarButtonActionPerformed(null);
        
        }
    }//GEN-LAST:event_passwordTxtKeyReleased

    private void userTxtKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_userTxtKeyReleased

        if(evt.getKeyCode()==java.awt.event.KeyEvent.VK_ENTER)
        {
            passwordTxt.requestFocus();
        
        }
    }//GEN-LAST:event_userTxtKeyReleased

    private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized

        //logger.info(this.getClass().getName()+":"+this.getSize().width+","+this.getSize().height);
    }//GEN-LAST:event_formComponentResized
    /**
     * Validar el usuario dentro de la bd para poder entrar al sistema
     * @param user El usuario a buscar en la bd
     * @param password password a buscar en la bd
     * @return regresa 0 en caso de que exista en la bd<br>
     * regresa -1 en caso de no se encontrado
     */
    private int validateUser()
    {
        int ret=-1;
        String user=userTxt.getText();
        String pass=new String(passwordTxt.getPassword());
        AccountUserDao acc=new AccountUserDao();
        Connection conn;
		try {
			///prendemos el mysql
			Dao.startupMySql();
			/////////////
			conn = Dao.getConnection();
			
			String [] user_tipo=acc.validUser(conn,user,pass);
			if(user_tipo!=null)
			{
				this.id_user=user_tipo[0];
				this.user=user_tipo[1];
				this.tipoUsuario=user_tipo[2];
				ret=0;
			}
			else
			{
				ret=-1;
			}
			conn.close();
		} catch (ClassNotFoundException e) {
			// 
			JOptionPane.showMessageDialog(this, "Error de Conexion a BD", "Error", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} catch (SQLException ex) {
			ex.printStackTrace();
			if(ex.getMessage().indexOf("Unknown database 'ccnetdb'")>=0)
			{
				logger.info("No hay base creada, vamos a crearla con los scripts");
				try {
					Dao.crearBDPrincipal();
					Dao.crearTablesDBPrincipal();
				} catch (Exception e) {
					e.printStackTrace();
				} 
				JOptionPane.showMessageDialog(this,"Base de datos inicializada, vuelva a proporcionar su usuario y password",
	                    "Base de datos",
	                    JOptionPane.WARNING_MESSAGE);
				
				ret=-2;
				
				
			}
			else
			{
				// TODO Auto-generated catch block
				JOptionPane.showMessageDialog(this,"Error de Conexion a BD",
	                    "Error en operacion de BD",
	                    JOptionPane.ERROR_MESSAGE);
				ex.printStackTrace();
				ret=-3;
			}
				
			
		}
        return ret;
    }
    private int validateUserToSwitch()
    {
        int ret=-1;
        String user=userTxt.getText();
        String pass=new String(passwordTxt.getPassword());
        AccountUserDao acc=new AccountUserDao();
        Connection conn;
		try {
			conn = Dao.getConnection();
			
			String [] user_tipo=acc.validUser(conn,user,pass);
			if(user_tipo!=null)
			{
				this.id_user=user_tipo[0];
				this.user=user_tipo[1];
				this.tipoUsuario=user_tipo[2];
				ret=0;
			}
			else
			{
				ret=-1;
			}
			conn.close();
		} catch (ClassNotFoundException e) {
			// 
			JOptionPane.showMessageDialog(this, "Error de Conexion a BD", "Error", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} catch (SQLException ex) {
			ex.printStackTrace();
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(this,"Error de Conexion a BD",
                    "Error en operacion de BD-"+ex.getMessage(),
                    JOptionPane.ERROR_MESSAGE);
			ex.printStackTrace();
			ret=-3;
			
				
			
		}
        return ret;
    }
    private void entrarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_entrarButtonActionPerformed
    	
    	int validUserCODE=-1 ;
    	if(innerLogin==null)
    		validUserCODE = validateUser();
    	else{
    		if(innerLogin!=null){
    			validUserCODE = validateUserToSwitch();
    		}
    	}
        if(validUserCODE==0)
        {
            doClose(RET_OK);
            innerLogin="logged";
        }
        else
        {
        	if(validUserCODE==-1)
        	JOptionPane.showMessageDialog(this,"Usuario o password erroneo",
                    "Error de Login",
                    JOptionPane.ERROR_MESSAGE);
        	
        }
    }//GEN-LAST:event_entrarButtonActionPerformed
    
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        doClose(RET_CANCEL);
    }//GEN-LAST:event_cancelButtonActionPerformed
    
    /** Closes the dialog */
    private void closeDialog(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeDialog
        doClose(RET_CANCEL);
    }//GEN-LAST:event_closeDialog
    
    private void doClose(int retStatus) {
        returnStatus = retStatus;
        setVisible(false);
        dispose();
    }

    public String getAuthorizedUser() {
        return user;
    }
    /**
    public static void main(String args[]) {
        LoginFrm nw=new LoginFrm(new javax.swing.JFrame(), true);
        nw.setVisible(true);
        if(nw.getReturnStatus()==LoginFrm.RET_OK)
            logger.info("regreso ok");
        else
            
            logger.info("regreso cancel");
        java.awt.EventQueue.invokeLoginFrm.RET_OK           public void run() {
                new NewOkCancelDialog(new javax.swing.JFrame(), true).setVisible(true);
            }
        });
    }
     **/
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel candadoLabel;
    private javax.swing.JButton entrarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPasswordField passwordTxt;
    private javax.swing.JTextField userTxt;
    // End of variables declaration//GEN-END:variables
    
    private int returnStatus = RET_CANCEL;

	/**
	 * @return the tipoUsuario
	 */
	public String getTipoUsuario() {
		return tipoUsuario;
	}

	/**
	 * @param tipoUsuario the tipoUsuario to set
	 */
	public void setTipoUsuario(String tipoUsuario) {
		this.tipoUsuario = tipoUsuario;
	}

	/**
	 * @return the id_user
	 */
	public String getId_user() {
		return id_user;
	}

	/**
	 * @param id_user the id_user to set
	 */
	public void setId_user(String id_user) {
		this.id_user = id_user;
	}

	public String getInnerLogin() {
		return innerLogin;
	}

	public void setInnerLogin(String innerLogin) {
		this.innerLogin = innerLogin;
	}
}
